<template>
    <div :style="styleObj">

        <el-container class="app-wrapper">
            <el-header ref="elHeader">
                <div style="float: left">
                    <span>
                        {{$t('bookMarks.bookmarksDirCount')}}
                        {{bookmarksDirCount}}
                    </span>
                    <span>
                        {{$t('bookMarks.bookmarksLinkCount')}}
                        {{bookmarksLinkCount}}
                    </span>
                </div>
                <div style="float: right">
                    <el-upload
                            style="display:inline-block;"
                            class="upload-demo" :show-file-list="false"
                            :auto-upload="true" action=""
                            :http-request="customUpload">
                        <el-button slot="trigger" size="small" type="primary"
                                   icon="icon-third-import">
                            <!--{{$t('bookMarks.import')}}-->
                        </el-button>
                    </el-upload>

                    <el-button size="small" type="primary" icon="icon-third-export">
                        <!--{{$t('bookMarks.export')}}-->
                    </el-button>
                    <el-button size="small" type="primary" icon="icon-third-clear">
                        <!--{{$t('bookMarks.clearAll')}}-->
                    </el-button>
                </div>
            </el-header>

            <el-main ref="elMain">
                <el-row>
                    <!-- 左侧树 -->
                    <el-col :span="6">

                        <el-tree accordion
                                 :data="bookmarks"
                                 :props="defaultProps"
                                 default-expand-all
                                 :expand-on-click-node="false"
                                 @node-click="handleNodeClick"
                                 ref="tree"
                                 class="treeStyle"
                                 :style="contentStyle"></el-tree>

                    </el-col>
                    <!-- 右侧内容 -->
                    <el-col :span="18">

                    </el-col>
                </el-row>
            </el-main>

        </el-container>

    </div>
</template>

<script>
    import fs from 'fs'
    import path from 'path'
    import xml2js from 'xml2js'

    import {DBInsert, DBFind, DBCount} from '@/api/NEDB/nedbApi'

    import {generatorFileMd5} from '@/utils/generatorFileMd5'

    export default {
        name: "bookMarks",

        data() {
            return {
                msg: '书签页面',
                styleObj: {
                    width: '100%',
                    height: '100%',
                    paddingTop: 0
                },
                id: 0,

                contentStyle:{
                    height: 0
                },

                defaultProps: {
                    label: 'label',         //用于展示的文字
                    children: 'children',   //子节点
                    id: 'id',
                    parent: 'parent',
                    hasChild: 'hasChild'
                },
                bookmarks:[],
                bookmarksDirCount:0,
                bookmarksLinkCount:0,
                canRemoveOrEdit: false
            }
        },

        created: function () {
            this.resetSize();
            this.init();
        },

        beforeRouteUpdate (to, from, next) {
            // 因为点击当前页面触发beforeRouteUpdate方法会触发两次
            // 第一次为两个时间都不为空，第二次为from的t不为空
            //
            // 从其他页面切换过来，to的t为空，from的t不为空
            //
            // 只有当前页面点击的才能触发beforeRouteUpdate方法

            if(to.path == from.path && typeof(to.query.t)!='undefined' && typeof(from.query.t)!='undefined'){
                // 两个时间都不是空的时候，表示是当前页面点击进入的
                // 设置beforeRouteUpdate的状态为允许触发
                this.$store.dispatch('setBeforeRouteUpdateActive', true);
                return;
            }

            // 增加判断：第一次切换进入页面时，to的t不为空，form的t为空；且this.$store.getters.beforeRouteUpdateActive为false
            // 重新进入页面：只有to的t为空，且设置允许触发的，才能触发，触发后就设置为false
            if(to.path == from.path && (
                (typeof(to.query.t)=='undefined' && this.$store.getters.beforeRouteUpdateActive)
                || (typeof(to.query.t)!='undefined' && typeof(from.query.t)=='undefined' && !this.$store.getters.beforeRouteUpdateActive)
            )){
                this.$store.dispatch('setBeforeRouteUpdateActive', false);
                this.init();
            }
        },

        methods: {
            resetSize(){
                try {
                    let fullHeight = document.getElementById("loadPageDiv").offsetHeight;
                    this.contentStyle.height = fullHeight - 80 + 'px';
                } catch (e) {
                }

                let that = this;
                if (that && !that._isDestroyed) {
                    setTimeout(() => {
                        if (that && !that._isDestroyed) {
                            that.resetSize();
                        }
                    }, 500);
                }
            },
            init() {
                this.bookmarks.push({
                    label: this.$t('bookMarks.rootBookMark'),
                    children:[]
                });
                this.loadAllDir();
                this.loadBookmarksDirCount();
                this.loadBookmarksLinkCount();
            },
            loadAllDir(){
                this.loadDirById(0, (nodes)=>function(){
                    this.bookmarks[0].children = nodes;
                });
            },
            loadDirById(id, callBack){
                let params={
                    hasChild: true,
                    parent: id
                };
                DBFind('BOOKMARK_DB',params, (data)=>{
                    const nodes = [];
                    for (let index in data) {
                        const children = [];

                        nodes.push({
                            label: data[index].dirName,
                            children: children,
                            id: data[index].id,
                            parent: data[index].parent,
                            hasChild: true
                        });
                    }

                    callBack(nodes);
                });
            },
            loadBookmarksDirCount(){
                let params={
                    hasChild: true
                };
                DBCount('BOOKMARK_DB',params, (data)=>{
                    this.bookmarksDirCount = data;
                });
            },
            loadBookmarksLinkCount(){
                let params={
                    hasChild: false
                };
                DBCount('BOOKMARK_DB',params, (data)=>{
                    this.bookmarksLinkCount = data;
                });
            },
            customUpload(fileobj){
                const that = this;
                generatorFileMd5(fileobj.file, md5 => {
                    let param = new FormData()
                    param.append('file',fileobj.file);
                    param.append('md5',md5);

                    // console.log(fileobj);

                    let filePath = fileobj.file.path;
                    fs.readFile(filePath, 'utf8', function (err, data) {
                        if (err) {
                            alert(err);
                        }

                        // console.log(data);
                        that.fnXML2Json(data);
                    });
                });
            },
            fnXML2Json(data){
                const that = this;
                // var builder = new xml2js.Builder(); // JSON -> XML
                let parser = new xml2js.Parser(); // XML -> JSON
                parser.parseString(data, function(err, result){
                    that.createBookMarks(result);
                });
            },
            createBookMarks(data){
                // 获取到书签的真实跟节点，构造数据

                let marks = data.html.body[0].dl[0].dt[0].dl[0].dt;
                var markList = [];
                var rootId = this.id;
                for(var i in marks){
                    let temp = marks[i];
                    markList.push(this.getMarksObj(temp, rootId));
                }

                // 重新构造数据数组，用于存储到数据库
                var tempMarks = this.getMarksArry(markList);
                this.saveBookMark(tempMarks);
            },
            getMarksObj(mark, parentId){
                this.id = this.id + 1;
                if(mark.a){
                    let a = mark.a[0]['$'];
                    return {
                        id: this.id,
                        parent: parentId,
                        hasChild: false,
                        href: a.href,
                        icon: a.icon ? a.icon : '',
                        title: mark.a[0]['_'],
                        keywords: '',
                        description: '',
                        clickCount: 0,
                        rate: 0,    //评分
                    };
                } else {
                    let tempArr = mark.dl[0].dt;
                    let dirName = mark.h3[0]['_'];
                    var tempList = {
                        id: this.id,
                        parent: parentId,
                        hasChild: true,
                        dirName: dirName,
                        childNodes: []
                    };
                    var rootId = this.id;
                    for(var i in tempArr){
                        tempList.childNodes.push(this.getMarksObj(tempArr[i], rootId));
                    }
                    return tempList;
                }
            },
            getMarksArry(markList){
                var tempMarks = [];

                // 获取mark数组，用于存储
                for(var i in markList){
                    if(markList[i].hasChild){
                        tempMarks.push({
                            id: markList[i].id,
                            parent: markList[i].parent,
                            hasChild: true,
                            dirName: markList[i].dirName,
                        });
                        let tempArr = this.getMarksArry(markList[i].childNodes);

                        tempMarks = tempMarks.concat(tempArr);
                    } else {
                        tempMarks.push(markList[i]);
                    }
                }

                return tempMarks;
            },
            saveBookMark(params){
                // 保存书签到数据库
                // params：可以是数组，也可以是对象

                DBInsert('BOOKMARK_DB', params, (data)=>{
                    console.log(data);
                });
            },
            handleNodeClick(data, node, tree) {
                this.canRemoveOrEdit = false;
            },
        }
    }
</script>

<style scoped>
    >>> .el-header {
        -webkit-app-region: drag;
        width: 100%;
        text-align: right;
        background: none;
    }

    .treeStyle{
        overflow-y: auto;
    }
</style>